package com.tg.app.activity.device.doorlock;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.constant.EventConstants;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.app.helper.DeviceHelper;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.msgex.helper.MessageHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DoorLockLaunchHelper {

    /**
     * 呼叫事件的有效期，定为 55s （设备60s下电）
     */
    public static final int CALL_VALID_DURATION = 55;

    private static final String TAG = "DoorLockLaunchHelper";

    private static final String SP_FILE_NAME = "TAN_GE_DOOR_LOCK";
    private static final String SP_KEY_ALL_DEVICES = "SP_KEY_ALL_DEVICES";
    private static final String SP_KEY_HAS_LAUNCH_CALL_SETTING = "SP_KEY_HAS_LAUNCH_CALL_SETTING_";
    private static final String SP_KEY_ACCEPT_CALL = "SP_KEY_ACCEPT_CALL_";
    private static final String SP_KEY_UUID_TO_DEVICE_ID = "SP_KEY_UUID_TO_DEVICE_ID_";

    private static final String TANGE_KEY_TUMBLE_DEVICE_UUID = "TANGE_KEY_TUMBLE_DEVICE_UUID";
    private static final String SPLIT_CHAR = "=";

    /**
     * 查询后台是否存在未接听的呼叫
     * @param activity
     */
    public static void checkIfExistNewCall(Activity activity) {

        if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
            return;
        }

        List<String> allDoorLockUUID = readAllDevices(activity);

        if (allDoorLockUUID == null || allDoorLockUUID.size() < 1) {
            return;
        }

        TGLog.i(TAG, "checkIfExistNewCall: exist door lock: " + allDoorLockUUID);

        final List<String> acceptCallUUID = new ArrayList<>();
        for (String uuid : allDoorLockUUID) {
            boolean accept = getAcceptCall(activity, uuid);
            if (accept) {
                acceptCallUUID.add(uuid);
            }
        }

        TGLog.i(TAG, "checkIfExistNewCall: accept call door lock: " + acceptCallUUID);

        if (acceptCallUUID.size() < 1) {
            TGLog.i(TAG, "checkIfExistNewCall: no door lock accept call , skip");
            return;
        }

        List<String> deviceIdList = new ArrayList<>();
        for (String uuid : acceptCallUUID) {
            SharedPreferences sharedPreferences = activity.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
            long id = sharedPreferences.getLong(SP_KEY_UUID_TO_DEVICE_ID + uuid, 0);
            if (id != 0) {
                deviceIdList.add(String.valueOf(id));
            }
        }

        TGLog.i(TAG, "checkIfExistNewCall: deviceIdList: " + deviceIdList);

        if (deviceIdList.size() < 1) {
            TGLog.i(TAG, "checkIfExistNewCall:deviceIdList empty , skip");
            return;
        }


        final HashMap<String, String> map = new HashMap<>();

        String device = deviceIdList.toString();
        device = device.replace("]", "");
        device = device.replace("[", "");
        map.put("device_id", device);

        String today = DateUtil.getTodayDate();
        long startTime = DateUtil.get2MillisYMDHHMMSS(today + " 00:00:00") / 1000;
        long endTime = System.currentTimeMillis() / 1000;

        map.put("start_timestamp", String.valueOf(startTime));
        map.put("end_timestamp", String.valueOf(endTime));
        map.put("page", String.valueOf(1));
        map.put("limit", String.valueOf(30));

        JSONObject object = JSON.parseObject(JSON.toJSONString(map));
        ArrayList<String> list = new ArrayList<>();
        list.add(EventConstants.DOORBELL_CALL);

        object.put("message_type", list);

        TGLog.i(TAG, "checkIfExistNewCall: final param: " + object);

        MessageHelper.getMessageList(object, new MessageHelper.MessageListener<MessageDataBean>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            protected void onSuccess(MessageDataBean content) {
                TGLog.i(TAG, "checkIfExistNewCall: onSuccess : ...");

                if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
                    TGLog.i(TAG, "checkIfExistNewCall onSuccess: activity empty");
                    return;
                }

                if (content != null && content.getItems() != null && content.getItems().size() > 0) {

                    MessageDataBean.ItemsBean bean = null;

                    for (MessageDataBean.ItemsBean eb : content.getItems()) {
                        if (eb != null && StringUtils.equalsIgnoreCase(eb.getTag(), EventConstants.DOORBELL_CALL)) {
                            bean = eb;
                            break;
                        }
                        long diffFromNow = System.currentTimeMillis() / 1000 - bean.getStart_ts();
                        if (diffFromNow > CALL_VALID_DURATION) {
                            TGLog.i(TAG, "checkIfExistNewCall onSuccess: would not search again because event too old !");
                            break;
                        }
                    }

                    if (bean == null) {
                        TGLog.i(TAG, "checkIfExistNewCall onSuccess: not found ring event !");
                        return;
                    }

                    // 检测最近一条事件，是否在60s内：

                    TGLog.i(TAG, "checkIfExistNewCall onSuccess: last event - device name = " + bean.getNickname());
                    TGLog.i(TAG, "checkIfExistNewCall onSuccess: last event - start time = " + bean.getStart_time());

                    long diff = System.currentTimeMillis() / 1000 - bean.getStart_ts();

                    TGLog.i(TAG, "checkIfExistNewCall onSuccess: last event time past = " + diff + ", bean.getStart_ts() = " + bean.getStart_ts() + ", System.currentTimeMillis() = " + System.currentTimeMillis());

                    if (diff < CALL_VALID_DURATION) {

                        try {
                            DeviceItem item = new DeviceItem();
                            item.name = bean.getNickname();
                            item.uuid = bean.getUuid();
                            item.id = Long.parseLong(bean.getDevice_id());
                            item.image_path = bean.getImage_path();
                            item.p2p_id = "100";
                            String attrs = DeviceTypeStorage.getDeviceAttrs(activity, item.uuid);
                            if (!StringUtils.isEmpty(attrs)){
                                item.attrs = attrs;
                            }

                            String type = DeviceTypeStorage.readDeviceType(activity, item.uuid);
                            if (!StringUtils.isEmpty(type)){
                                item.device_type = type;
                            }



                        } catch (Throwable ex) {
                            TGLog.i(TAG, "checkIfExistNewCall: onSuccess : error while launch: " + ex);
                        }

                    } else {
                        TGLog.i(TAG, "checkIfExistNewCall: onSuccess : out of time !");
                    }


                    // 检测这条事件，有没有内挂断过？
                } else {
                    TGLog.i(TAG, "checkIfExistNewCall: onSuccess : no event !");
                }
            }

            @Override
            protected void onError(int errorCode, String errorInfo){
                TGLog.i(TAG, "checkIfExistNewCall: onError " + errorCode + " , " + errorInfo);
            }

            @Override
            protected void onFinish() { }
        });
    }



    public static List<String> readAllDevices(Context context) {
        List<String> ret = new ArrayList<>();
        if (context == null) {
            return ret;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        String saved = sharedPreferences.getString(SP_KEY_ALL_DEVICES, "");
        if (!TextUtils.isEmpty(saved)) {
            String[] split = saved.split(SPLIT_CHAR);

            if (split != null && split.length > 0) {
                for (String s : split) {
                    if (!TextUtils.isEmpty(s)) {
                        ret.add(s);
                    }
                }
            }
        }
        return ret;
    }



    public static void setAcceptCall(Context context, DeviceItem item, boolean accept) {
        if (context == null || item == null) {
            return;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(SP_KEY_ACCEPT_CALL  + item.uuid, accept);
        editor.apply();
    }

    public static boolean getAcceptCall(Context context, DeviceItem item) {
        if (context == null || item == null) {
            return false;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(SP_KEY_ACCEPT_CALL + item.uuid, true);
    }

    public static boolean getAcceptCall(Context context, String uuid) {
        if (context == null || uuid == null) {
            return false;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(SP_KEY_ACCEPT_CALL + uuid, true);
    }

    public static void setHasLaunchCallSetting(Context context, DeviceItem item) {
        if (context == null || item == null) {
            return;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(SP_KEY_HAS_LAUNCH_CALL_SETTING  + item.uuid, true);
        editor.apply();
    }

    public static void saveAllLockBellDevice(Context context, List<DeviceItem> deviceItems) {
        if (context == null) {
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();

        if (deviceItems != null && deviceItems.size() > 0) {
            for (DeviceItem item : deviceItems) {
                if (item != null && DeviceHelper.isLockBell(item)) {
                    stringBuilder.append(item.uuid).append(SPLIT_CHAR);

                    SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putLong(SP_KEY_UUID_TO_DEVICE_ID  + item.uuid, item.id);
                    editor.apply();
                }
            }
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SP_KEY_ALL_DEVICES, stringBuilder.toString());
        editor.apply();
    }

    public static void saveAllTumbleDevice(Context context, List<DeviceItem> deviceItems) {
        if (context == null) {
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        if (deviceItems != null && deviceItems.size() > 0) {
            for (DeviceItem item : deviceItems) {
                if (item != null && DeviceHelper.isSupportTumble(item)) {
                    stringBuilder.append(item.uuid).append(SPLIT_CHAR);
                }
            }
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(TANGE_KEY_TUMBLE_DEVICE_UUID, stringBuilder.toString());
        editor.apply();

    }


    /**
     * 门铃呼叫是否已经设置
     *
     * @param context
     * @return
     */
    public static boolean isDoorLockCallEnabled(Context context, DeviceItem item) {
        if (context == null || item == null) {
            return false;
        }

        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(SP_KEY_HAS_LAUNCH_CALL_SETTING + item.uuid, false)
                && getAcceptCall(context, item);
    }
}
